import asyncio
import random
import pyautogui

from core.base_controller import BaseController
from core.utils import focus_wow

class BakuController(BaseController):
    async def focus_wow(self):
        """ 定时任务 focus_wow """
        while True:
            await self.ws_client.broadcast_log(message_content="focus_wow", message_type=1)
            focus_wow()
            try:
                await asyncio.sleep(random.uniform(5, 10))  # 任务可以被取消
            except asyncio.CancelledError:
                await self.ws_client.broadcast_log(message_content="focus_wow 任务被取消", message_type=2)
                break  # 任务被取消后退出循环

    async def press_8(self):
        """ 定时任务 press_8 """
        while True:
            await self.ws_client.broadcast_log(message_content="press_8", message_type=1)
            pyautogui.press('8')
            try:
                await asyncio.sleep(random.uniform(1.1, 2.4))  # 任务可以被取消
            except asyncio.CancelledError:
                await self.ws_client.broadcast_log(message_content="press_8 任务被取消", message_type=2)
                break  # 任务被取消后退出循环

    async def press_9(self):
        """ 定时任务 press_9 """
        while True:
            await self.ws_client.broadcast_log(message_content="press_9", message_type=1)
            pyautogui.press('9')
            try:
                await asyncio.sleep(random.uniform(0.5, 1.5))  # 任务可以被取消
            except asyncio.CancelledError:
                await self.ws_client.broadcast_log(message_content="press_9 任务被取消", message_type=2)
                break  # 任务被取消后退出循环

    async def start(self):
        """ 启动所有定时任务 """
        await self.stop_all_task()  # 停止之前所有任务
        
        focus_task = asyncio.create_task(self.focus_wow())  # 创建任务
        self.add_task(focus_task)  # 添加任务到列表
        
        task_8 = asyncio.create_task(self.press_8())  # 创建任务
        self.add_task(task_8)  # 添加任务到列表
        
        task_9 = asyncio.create_task(self.press_9())  # 创建任务
        self.add_task(task_9)  # 添加任务到列表

    async def stop(self):
        """ 停止定时器 """
        await self.stop_all_task()  # 停止所有任务